import React, {Component} from 'react'
import { Menu, Icon, Spin, Modal } from 'antd';
import { Link } from 'react-router'
import { fetchData } from "../../components/AjaxConsumer";
import cookie from 'react-cookie';


const SubMenu = Menu.SubMenu;
export default class SideAntd extends Component {
    constructor(props) {
        super(props);

        let lantype = window.localStorage.getItem('language');
        let ifCn = true;
        // if (lantype == 'CN') {
        //     this.ifCn = true;
        // } else if (lantype == 'EN') {
        //     console.log("英文环境");
        //     this.ifCn = false;
        // }
      if (lantype == 'EN') {
            console.log("英文环境");
            this.ifCn = false;
        }  else {
            this.ifCn = true;
        }  

        this.state = {
            current: '0',
            openKeys: [], //默认展开的层级
            resData: null,
            ifCN: this.ifCn //是否为中文，true为中文，false为英文
        };

        this.childResourceMap = {}; //菜单层级关系
    }

    handleClick = (e) => {
        this.setState({
            current: e.key,
        });
        let menuOpen = {
            current: e.key,
            openKeys: this.state.openKeys
        };
        cookie.save('menuOpen', menuOpen, { path: '/'});

    };
    onOpenChange = (openKeys) => {
        const state = this.state;
        // console.log("openKeys数组？",openKeys)
        // console.log("state.openKeys数组？",state.openKeys)
        // if(Array.prototype.find){
        //     console.log("支持es6find")
        // }else{
        //     console.log("不支持支持es6find")            
        // }
        //如果不支持es6 find方法，重写find
        Array.prototype.find = Array.prototype.find || function (fn, context) {
            if (typeof fn === "function") {
              for (var k = 0, length = this.length; k < length; k++) {
                if (fn.call(context, this[k], k, this)) {
                  return this[k];
                }
              }
            }
            return undefined;
          };
        const latestOpenKey = openKeys.find((key) =>{ 
            return !(state.openKeys.indexOf(key) > -1)
        });
        //自己用for循环替代find
        // for(let i=0;i<openKeys.length;i++){
        //     if( !(state.openKeys.indexOf(openKeys[i]) > -1)){
        //          var latestOpenKey= openKeys[i]
        //     }
        // }
        // console.log("latestOpenKey的return值",latestOpenKey)

        const latestCloseKey = state.openKeys.find(key => !(openKeys.indexOf(key) > -1));
        //自己用for循环替代find
        // for(let i=0;i<state.openKeys.length;i++){
        //     if( !(openKeys.indexOf(state.openKeys[i]) > -1)){
        //          var latestCloseKey= state.openKeys[i]
        //     }

        // }
        
        // console.log("latestCloseKey的return值",latestCloseKey)

        let nextOpenKeys = [];
        if (latestOpenKey) {
            nextOpenKeys = this.getAncestorKeys(latestOpenKey).concat(latestOpenKey);
        }
        if (latestCloseKey) {
            nextOpenKeys = this.getAncestorKeys(latestCloseKey);
        }
        this.setState({ openKeys: nextOpenKeys });
    };
    getAncestorKeys = (key) => {
        const map = this.childResourceMap;
        return map[key] || [];
    };
    refreshLeftMenu = () => {
        const options= {
            url: this.props.url,
            type: 'get'
        };
        fetchData(this, options, (resData) => {
            let menuOpen = cookie.load('menuOpen');
            if(menuOpen){
                this.setState({
                    current: menuOpen.current,
                    openKeys: menuOpen.openKeys, //默认展开的层级
                    resData: resData
                });
            }else{
                this.setState({
                    resData: resData
                });
            }

        });
    };
    linkClick = (menuItemKey, resourceName) => {
        this.props.addTabs(menuItemKey, resourceName);
    };
    componentDidMount(){
        this.refreshLeftMenu();
    }
    componentWillMount(){
        if (window.navigator.userAgent.indexOf('Trident') != -1) {
            Modal.info({
                title: "提示",
                content: "请切换到急速模式（谷歌内核）或使用Google浏览器。当前兼容模式影响使用体验"
            }); 
            }
    }

    render() {
        let menuData = this.state.resData;
        let ifCN = this.state.ifCN;
        let view,subMenu;
        if (menuData == null) {
            view = <Spin size="large"/>
        } else {
            let menuItemKey = 0,
                subMenuKey = 0;
            let loop = (data, subMenuParentKey) => {
                return data.map((item) => {
                    menuItemKey += 1;
                    if (item.childResource) {
                        subMenuKey += 1;
                        if(typeof(subMenuParentKey) != "undefined"){
                            this.childResourceMap["sub"+subMenuKey] = ["sub"+subMenuParentKey];
                        }
                        return (
                            <SubMenu key={"sub" + subMenuKey} title={<span>{ifCN ? item.resourceName : item.engResourceName}</span>}>
                                {loop(item.childResource, subMenuKey)}
                            </SubMenu>
                        );
                    }
                    if (item.dicCode != this.props.currentSystem) {
                        return <Menu.Item key={menuItemKey}><a href={item.href}>{ifCN ? item.resourceName : item.engResourceName}</a></Menu.Item>;
                    }
                    return <Menu.Item key={menuItemKey}><Link onClick={this.linkClick.bind(this, menuItemKey, item.resourceName)} to={item.href} >{ifCN ? item.resourceName : item.engResourceName}</Link></Menu.Item>;
                });
            };
            subMenu = menuData.data.map((el) => {
                subMenuKey += 1;
                if(el.childResource){
                    return (
                        <SubMenu key={"sub" + subMenuKey}
                                 title={<span><Icon type={el.iconClass}/><span>{ifCN ? el.resourceName : el.engResourceName}</span></span>}>
                            {loop(el.childResource, subMenuKey)}
                        </SubMenu>
                    )
                }else{
                    return (
                        <SubMenu key={"sub" + subMenuKey}
                                 title={<span><Icon type={el.iconClass}/><span>{ifCN ? el.resourceName : el.engResourceName}</span></span>}>
                        </SubMenu>
                    )
                }
            });
            view = (
                <Menu
                    theme="dark"
                    mode="inline"
                    style={{width: 210}}
                    onClick={this.handleClick}
                    selectedKeys={[this.state.current]}
                    openKeys={this.state.openKeys}
                    onOpenChange={this.onOpenChange}
                >
                    {subMenu}
                </Menu>
            )
        }
        return (
            <div>
                {view}
            </div>
        );
    }
}